<template>
    <div>
      <div class="search-container">
        <el-input style="width: 200px; margin-right: 10px;" suffix-icon="el-icon-search" :placeholder="$t('common.pleaseEnter') + ' ' + $t('role.name')" v-model="roleName"/>
        <el-button type="primary" @click="loadData">{{ $t('common.search') }}</el-button>
        <el-button @click="resetSearch">{{ $t('common.reset') }}</el-button>
      </div>
      <div class="operation-container">
        <el-button type="primary" @click="handleAdd" class="operation-button">
          <i class="el-icon-plus"></i> {{ $t('role.add') }}
        </el-button>
        <el-popconfirm :title="$t('common.deleteConfirm')" @confirm="handleDeleteBatch" class="ml-5">
          <el-button type="danger" slot="reference" class="operation-button" :disabled="rawId.length === 0">
            <i class="el-icon-delete"></i> {{ $t('common.delete') }}
          </el-button>
        </el-popconfirm>
      </div>
      <div class="table-container">
        <el-table :data="tableData" border stripe :header-cell-style="headClass" :cell-style="cellClass"
                  @selection-change="handleSelectionChange" :max-height="tableHeight"
                  v-loading="loading">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" min-width="80"></el-table-column>
          <el-table-column prop="name" :label="$t('role.name')" min-width="120"></el-table-column>
          <el-table-column prop="type" :label="$t('permission.type')" min-width="120">
            <template slot-scope="scope">
              <el-tag :type="getTypeTagType(scope.row.type)">{{ getRoleTypeText(scope.row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" :label="$t('common.status')" min-width="100">
            <template slot-scope="scope">
              <el-tag :type="getRoleStatusType(scope.row.status)">
                {{ getRoleStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- PC端操作列 -->
          <el-table-column :label="$t('common.operation')" min-width="280" fixed="right" v-if="!isMobile">
            <template slot-scope="scope">
              <div class="operation-buttons">
                <el-button type="primary" size="mini" @click="handleMenu(scope.row)">
                  <i class="el-icon-setting"></i> {{ $t('permission.title') }}
                </el-button>
                <el-button type="warning" size="mini" @click="handleEdit(scope.$index, scope.row)">
                  <i class="el-icon-edit"></i> {{ $t('common.edit') }}
                </el-button>
                <el-popconfirm :title="$t('common.deleteConfirm')" @confirm="handleDelete(scope.$index, scope.row)">
                  <el-button type="danger" size="mini" slot="reference">
                    <i class="el-icon-delete"></i> {{ $t('common.delete') }}
                  </el-button>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
          
          <!-- 移动端操作列 -->
          <el-table-column :label="$t('common.operation')" width="100" fixed="right" v-if="isMobile">
            <template slot-scope="scope">
              <el-popover
                placement="left"
                width="160"
                trigger="click">
                <div class="mobile-operation-buttons">
                  <el-button 
                    type="text" 
                    size="mini" 
                    @click="handleMenu(scope.row)">
                    <i class="el-icon-setting"></i> {{ $t('permission.title') }}
                  </el-button>
                  <el-button 
                    type="text" 
                    size="mini" 
                    @click="handleEdit(scope.$index, scope.row)">
                    <i class="el-icon-edit"></i> {{ $t('common.edit') }}
                  </el-button>
                  <el-popconfirm :title="$t('common.deleteConfirm')" @confirm="handleDelete(scope.$index, scope.row)">
                    <el-button 
                      type="text" 
                      size="mini" 
                      slot="reference"
                      class="delete-button">
                      <i class="el-icon-delete"></i> {{ $t('common.delete') }}
                    </el-button>
                  </el-popconfirm>
                </div>
                <el-button slot="reference" type="primary" size="mini">
                  {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
                </el-button>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            :layout="paginationLayout"
            :total="total">
        </el-pagination>
      </div>
  
      <!-- 添加或编辑角色弹窗 -->
      <el-dialog :title="$t('role.info')" :visible.sync="dialogFormVisible" width="90%" :fullscreen="isMobile">
        <el-form :model="form" :rules="rules" ref="roleForm" label-width="100px" :inline="!isMobile" label-position="left">
          <el-form-item :label="$t('role.name')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('common.pleaseEnter') + ' ' + $t('role.name')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('permission.type')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('common.pleaseSelect') + ' ' + $t('permission.type')">
              <el-option :label="$t('user.admin')" :value="0"></el-option>
              <el-option :label="$t('user.teacher')" :value="1"></el-option>
              <el-option :label="$t('user.student')" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('common.status')" prop="status">
            <el-select v-model="form.status" :placeholder="$t('common.pleaseSelect') + ' ' + $t('common.status')">
              <el-option :label="$t('common.enabled')" :value="1"></el-option>
              <el-option :label="$t('common.disabled')" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('common.description')" prop="description" :span="24">
            <el-input type="textarea" v-model="form.description" :placeholder="$t('common.pleaseEnter') + ' ' + $t('common.description')" :rows="3"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $t('common.cancel') }}</el-button>
          <el-button type="primary" @click="save()" :loading="saveLoading">{{ $t('common.confirm') }}</el-button>
        </div>
      </el-dialog>
  
      <!-- 设置权限弹窗 -->
      <el-dialog :title="$t('permission.title')" :visible.sync="dialogMenuVisible" width="90%" :fullscreen="isMobile">
        <div class="permission-header">
          <h4>{{ $t('role.name') }}: <el-tag type="primary">{{ currentRole.name }}</el-tag></h4>
          <div class="permission-actions">
            <el-button size="small" type="primary" @click="checkAll">{{ $t('common.all') }}</el-button>
            <el-button size="small" @click="checkNone">{{ $t('common.cancel') }}</el-button>
          </div>
        </div>
        <el-divider></el-divider>
        <div class="permission-tree-container" v-loading="treeLoading">
          <el-tree
            :props="props"
            :data="rightData"
            show-checkbox
            node-key="id"
            ref="tree"
            :default-expand-all="true"
            :check-strictly="true"
            :render-content="renderContent"
            @check-change="handleCheckChange">
          </el-tree>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogMenuVisible = false">{{ $t('common.cancel') }}</el-button>
          <el-button type="primary" @click="handleRight()" :loading="savePermissionLoading">{{ $t('common.confirm') }}</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import ElementUI from "element-ui";
  
  export default {
    name: "RoleManage",
    data() {
      return {
        tableData: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
        roleName: "",
        loading: false,
        saveLoading: false,
        treeLoading: false,
        savePermissionLoading: false,
        dialogFormVisible: false,
        dialogMenuVisible: false,
        form: {
          name: '',
          type: 2,
          status: 1,
          description: ''
        },
        // 角色类型映射
        roleTypeMap: {
          0: { text: 'user.admin', type: 'danger' },
          1: { text: 'user.teacher', type: 'warning' }, 
          2: { text: 'user.student', type: 'success' }
        },
        // 角色状态映射（根据SQL字段定义）
        roleStatusMap: {
          0: { text: 'common.disabled', type: 'danger' },  // 冻结
          1: { text: 'common.enabled', type: 'success' },  // 正常
          2: { text: 'common.deleted', type: 'info' }      // 删除
        },
        rules: {
          name: [
            { required: true, message: this.$t('common.pleaseEnter') + ' ' + this.$t('role.name'), trigger: 'blur' },
            { min: 2, max: 50, message: this.$t('common.lengthLimit', { min: 2, max: 50 }), trigger: 'blur' }
          ],
          type: [
            { required: true, message: this.$t('common.pleaseSelect') + ' ' + this.$t('permission.type'), trigger: 'change' }
          ],
          status: [
            { required: true, message: this.$t('common.pleaseSelect') + ' ' + this.$t('common.status'), trigger: 'change' }
          ]
        },
        rawId: [],
        roleId: 0,
        currentRole: {},
        rightData: [],
        props: {
          label: 'name',
          children: 'children'
        },
        isMobile: false,
        tableHeight: 650,
        paginationLayout: "total, sizes, prev, pager, next, jumper",
        screenWidth: document.body.clientWidth
      }
    },
    created() {
      this.loadData()
      this.checkScreenSize()
    },
    mounted() {
      window.addEventListener('resize', this.checkScreenSize)
      this.checkScreenSize()
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.checkScreenSize)
    },
    methods: {
      // 检查屏幕尺寸并设置相应的布局
      checkScreenSize() {
        this.screenWidth = document.body.clientWidth
        this.isMobile = this.screenWidth < 768
        
        // 根据屏幕尺寸调整分页控件布局
        if (this.isMobile) {
          this.paginationLayout = "prev, pager, next"
          this.tableHeight = 450
        } else {
          this.paginationLayout = "total, sizes, prev, pager, next, jumper"
          this.tableHeight = 650
        }
      },
      // 获取角色类型标签样式
      getTypeTagType(type) {
        return (this.roleTypeMap[type] || { type: 'info' }).type;
      },
      // 获取角色类型显示文本
      getRoleTypeText(type) {
        const typeInfo = this.roleTypeMap[type] || { text: 'common.unknown' };
        return this.$t(typeInfo.text);
      },
      // 获取角色状态标签样式
      getRoleStatusType(status) {
        return (this.roleStatusMap[status] || { type: 'info' }).type;
      },
      // 获取角色状态显示文本
      getRoleStatusText(status) {
        const statusInfo = this.roleStatusMap[status] || { text: 'common.unknown' };
        return this.$t(statusInfo.text);
      },
      // 重置搜索条件
      resetSearch() {
        this.roleName = ""
        this.loadData()
      },
      // 全选权限
      checkAll() {
        this.$refs.tree.setCheckedNodes(this.rightData)
      },
      // 取消全选权限
      checkNone() {
        this.$refs.tree.setCheckedKeys([])
      },
      //设置表头
      headClass() {
        return 'background:#E6F1FF;color:#368CFF;font-size:13px;text-align: center;'
      },
      //设置表样式
      cellClass() {
        return 'text-align: center;'
      },
      //改变显示条数时调用
      handleSizeChange(pageSize) {
        this.pageSize = pageSize
        this.loadData()
      },
      // 改变页码时调用
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage
        this.loadData()
      },
      //添加角色
      save() {
        this.$refs.roleForm.validate((valid) => {
          if (valid) {
            this.saveLoading = true
            this.$axios.post("/role/add", this.form).then(res => {
              let data = res;
              if (data.code === 200) {
                ElementUI.Message.success(this.$t('common.operationSuccess'))
                this.dialogFormVisible = false;
                this.loadData()
              } else {
                ElementUI.Message.error(data.msg || this.$t('common.operationFailed'))
              }
            }).catch(err => {
              console.error(this.$t('common.operationFailed'), err)
              ElementUI.Message.error(this.$t('common.operationFailed'))
            }).finally(() => {
              this.saveLoading = false
            })
          } else {
            return false;
          }
        });
      },
      // 添加角色
      handleAdd() {
        this.dialogFormVisible = true
        this.form = {
          name: '',
          type: 2,
          status: 1,
          description: ''
        }
        // 重置表单验证
        if (this.$refs.roleForm) {
          this.$refs.roleForm.resetFields()
        }
      },
      // 删除角色
      handleDelete(index, row) {
        this.loading = true
        this.$axios.delete("/role/delete/" + row.id).then(res => {
          let data = res;
          if (data.code === 200) {
            ElementUI.Message.success(this.$t('common.operationSuccess'))
            this.loadData()
          } else {
            ElementUI.Message.error(data.msg || this.$t('common.operationFailed'))
          }
        }).catch(err => {
          console.error(this.$t('common.operationFailed'), err)
          ElementUI.Message.error(this.$t('common.operationFailed'))
        }).finally(() => {
          this.loading = false
        })
      },
      // 批量删除
      handleDeleteBatch() {
        if (this.rawId.length === 0) {
          ElementUI.Message.warning(this.$t('role.selectFirst'))
          return
        }
        
        this.loading = true
        this.$axios.post("/role/delete/batch/", this.rawId).then(res => {
          let data = res;
          if (data.code === 200) {
            ElementUI.Message.success(this.$t('common.operationSuccess'))
            this.loadData()
          } else {
            ElementUI.Message.error(data.msg || this.$t('common.operationFailed'))
          }
        }).catch(err => {
          console.error(this.$t('common.operationFailed'), err)
          ElementUI.Message.error(this.$t('common.operationFailed'))
        }).finally(() => {
          this.loading = false
        })
      },
      // 编辑角色
      handleEdit(index, row) {
        this.dialogFormVisible = true
        this.form = JSON.parse(JSON.stringify(row))
        // 重置表单验证
        this.$nextTick(() => {
          if (this.$refs.roleForm) {
            this.$refs.roleForm.resetFields()
          }
        })
      },
      //多选框事件
      handleSelectionChange(raw) {
        this.rawId = []
        for (let i = 0; i < raw.length; i++) {
          this.rawId.push(raw[i].id);
        }
      },
      //加载数据
      loadData() {
        this.loading = true
        this.$axios.get("/role/list", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            roleName: this.roleName,
          }
        }).then(res => {
          let data = res.data;
          this.tableData = data.records;
          this.total = data.total;
        }).catch(err => {
          console.error("加载角色列表失败", err)
          ElementUI.Message.error("加载数据失败，请稍后重试")
        }).finally(() => {
          this.loading = false
        })
      },
      //  加载权限菜单
      handleMenu(row) {
        this.roleId = row.id;
        this.currentRole = row;
        this.dialogMenuVisible = true;
        this.treeLoading = true;
        
        Promise.all([
          this.$axios.get("/right/all"),
          this.$axios.get("/role-right/" + row.id)
        ]).then(([rightRes, roleRightRes]) => {
          // 处理权限树数据
          this.rightData = this.handleRightData(rightRes.data);
          
          // 等待DOM更新
          this.$nextTick(() => {
            // 先清空所有选中状态
            this.$refs.tree.setCheckedKeys([]);
            
            // 设置选中状态
            if (roleRightRes.code === 200 && Array.isArray(roleRightRes.data)) {
              this.$refs.tree.setCheckedKeys(roleRightRes.data);
            }
          });
        }).catch(err => {
          console.error("加载权限数据失败", err);
          ElementUI.Message.error("加载权限数据失败，请稍后重试");
        }).finally(() => {
          this.treeLoading = false;
        });
      },
      // 处理权限数据，构建树形结构
      handleRightData(data) {
        const map = {};
        const result = [];
        
        // 先将所有项目存入map
        data.forEach(item => {
          map[item.id] = { 
            ...item, 
            children: [],
            disabled: item.status === 0  // 如果权限状态为禁用，则禁用选择
          };
        });
        
        // 构建树形结构
        data.forEach(item => {
          const node = map[item.id];
          if (item.pid === 0) {
            result.push(node);
          } else {
            if (map[item.pid]) {
              map[item.pid].children.push(node);
            } else {
              // 如果找不到父节点，作为顶级节点处理
              result.push(node);
            }
          }
        });
        
        return result;
      },
      // 添加权限事件
      handleRight() {
        this.savePermissionLoading = true;
        
        // 获取所有选中的节点key
        const checkedKeys = this.$refs.tree.getCheckedKeys();
        // 获取所有半选中的节点key（父节点）
        const halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
        
        // 合并完整的权限ID列表
        const roleRight = {
          roleId: this.roleId,
          rightIds: [...new Set([...checkedKeys, ...halfCheckedKeys])]
        };
        
        this.$axios.post("/role-right/set", roleRight).then(res => {
          if (res.code === 200) {
            ElementUI.Message.success(res.msg || this.$t('common.operationSuccess'));
            this.dialogMenuVisible = false;
          } else {
            ElementUI.Message.error(res.msg || this.$t('common.operationFailed'));
          }
        }).catch(err => {
          console.error(this.$t('common.operationFailed'), err);
          ElementUI.Message.error(this.$t('common.operationFailed'));
        }).finally(() => {
          this.savePermissionLoading = false;
        });
      },
      // 权限树变化时触发
      handleCheckChange(data, checked, indeterminate) {
        // 获取当前节点的父节点路径
        const parentKey = this.getParentKey(this.rightData, data.id);
        if (checked && parentKey) {
          // 如果是选中状态，确保父节点也被选中
          this.$refs.tree.setChecked(parentKey, true);
        }
      },
      // 获取节点的父节点ID
      getParentKey(data, nodeId, parent = null) {
        for (const item of data) {
          if (item.id === nodeId) {
            return parent;
          }
          if (item.children) {
            const parentKey = this.getParentKey(item.children, nodeId, item.id);
            if (parentKey !== null) {
              return parentKey;
            }
          }
        }
        return null;
      },
      // 自定义树节点渲染内容
      renderContent(h, { node, data }) {
        return h('span', {
          class: 'custom-tree-node'
        }, [
          h('i', {
            class: data.icon || 'el-icon-folder',
            style: {
              marginRight: '8px',
              fontSize: '16px',
              color: '#409EFF'
            }
          }),
          h('span', {
            class: 'node-label',
            style: {
              fontSize: '14px'
            }
          }, node.label),
          data.url ? h('span', {
            class: 'node-path',
            style: {
              marginLeft: '8px',
              color: '#909399',
              fontSize: '12px'
            }
          }, data.url) : null
        ]);
      }
    }
  };
  </script>
  
  <style scoped>
  .search-container {
    margin: 10px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  
  .operation-container {
    margin: 10px;
    text-align: left;
  }
  
  .table-container {
    width: 100%;
    overflow-x: auto;
  }
  
  .pagination-container {
    padding: 15px 0;
    display: flex;
    justify-content: center;
  }
  
  .operation-buttons {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 5px;
  }
  
  .operation-button {
    margin-bottom: 5px;
    margin-right: 5px;
  }
  
  .permission-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding: 0 20px;
  }
  
  .permission-header h4 {
    margin: 0;
    font-size: 16px;
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  .permission-actions {
    display: flex;
    gap: 10px;
  }
  
  .permission-tree-container {
    max-height: 600px;
    overflow-y: auto;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fff;
  }
  
  .permission-tree-container :deep(.el-tree) {
    background-color: transparent;
  }
  
  .permission-tree-container :deep(.el-tree-node__content) {
    height: 40px;
    border-radius: 4px;
    transition: all 0.3s;
  }
  
  .permission-tree-container :deep(.el-tree-node__content:hover) {
    background-color: #f5f7fa;
  }
  
  .permission-tree-container :deep(.custom-tree-node) {
    flex: 1;
    display: flex;
    align-items: center;
    font-size: 14px;
  }
  
  .permission-tree-container :deep(.el-tree-node__children) {
    padding-left: 20px;
  }
  
  .mobile-operation-buttons {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .mobile-operation-buttons .el-button {
    margin-left: 0;
    margin-bottom: 8px;
    width: 100%;
    text-align: left;
  }
  
  .mobile-operation-buttons .el-button:last-child {
    margin-bottom: 0;
  }
  
  .mobile-operation-buttons .delete-button {
    color: #F56C6C;
  }
  
  .custom-tree-node {
    display: flex;
    align-items: center;
    padding: 0 8px;
  }
  
  .node-label {
    margin-right: 8px;
    font-weight: 500;
  }
  
  .node-path {
    padding: 2px 6px;
    background-color: #f5f7fa;
    border-radius: 3px;
    font-family: monospace;
  }
  
  @media screen and (max-width: 768px) {
    .search-container {
      flex-direction: column;
      align-items: flex-start;
    }
    
    .search-container .el-input {
      width: 100%;
      margin-bottom: 10px;
      margin-right: 0;
    }
    
    .search-container .el-button {
      margin-bottom: 5px;
    }
    
    .el-table {
      width: 100%;
      font-size: 12px;
    }
    
    .el-button {
      padding: 7px 10px;
      font-size: 12px;
    }
    
    .el-form-item {
      width: 100%;
    }
    
    .el-select {
      width: 100%;
    }
    
    .permission-header {
      flex-direction: column;
      align-items: flex-start;
      padding: 0 10px;
    }
    
    .permission-actions {
      margin-top: 10px;
    }
    
    .permission-tree-container {
      padding: 10px;
      max-height: 400px;
    }
  }
  </style>